<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Extend\Event;

use Admin\Service\SystemManager;
use Doctrine\ORM\EntityManager;
use Extend\Service\SystemNoticeManager;
use Laminas\EventManager\Event;
use Laminas\EventManager\EventManagerInterface;
use Laminas\EventManager\ListenerAggregateInterface;
use Laminas\Mvc\I18n\Translator;
use User\Service\Common\AppLogin\FacebookLogin;
use User\Service\Common\AppLogin\GoogleLogin;

class ExtendListener implements ListenerAggregateInterface
{
    protected $listeners = [];

    private $entityManager;
    private $systemNoticeManager;
    private $systemManager;

    private $translator;

    public function __construct(
        EntityManager   $entityManager,
        SystemNoticeManager $systemNoticeManager,
        SystemManager   $systemManager,
        Translator      $translator
    )
    {
        $this->entityManager = $entityManager;
        $this->systemNoticeManager = $systemNoticeManager;
        $this->systemManager = $systemManager;

        $this->translator   = $translator;
    }

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $shareEvents = $events->getSharedManager();

        //关闭插件的处理
        $this->listeners[] = $shareEvents->attach(
            'Extend\Controller\IndexController', 'extend-plugin.off.post', [$this, 'onOffPlugin']
        );

        //客户设置
        $this->listeners[] = $shareEvents->attach(
            'Admin\Controller\CustomerSetController', 'system.customer-set.show', [$this, 'onCustomerSet']
        );

        //前台商品咨询
        /*$this->listeners[] = $shareEvents->attach(
            'Shop\Controller\GoodsController', 'shop.goodsInfo.goods.addConsult', [$this, 'onAddGoodsConsultSystemNotice']
        );*/

        //前台商品评价
        /*$this->listeners[] = $shareEvents->attach(
            'Shop\Controller\HomeOrderController', 'shop.order.evaluation.post', [$this, 'onAddOrderGoodsEvaluationSystemNotice']
        );*/
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            $events->detach($listener);
            unset($this->listeners[$index]);
        }
    }

    /**
     * 关闭插件时，对应的一些操作
     * @param Event $event
     * @return void
     */
    public function onOffPlugin(Event $event)
    {
        $pluginInfo = $event->getParam('pluginInfo');

        if (in_array($pluginInfo->getPluginCode(), ['PluginGoogleLogin', 'PluginFacebookLogin'])) {
            if ($pluginInfo->getPluginCode() == 'PluginGoogleLogin') $this->systemManager->deleteSystem(['google_login_state', 'google_app_id', 'google_app_key'], 'customer');
            if ($pluginInfo->getPluginCode() == 'PluginFacebookLogin') $this->systemManager->deleteSystem(['facebook_login_state', 'facebook_app_id', 'facebook_app_key'], 'customer');
            $event->getTarget()->createConfig()->createCustomer();
        }
    }

    /**
     * 第三方登录设置，因为登录插件，不会以模块的方式运行，所以这里对其进行表单添加
     * @param Event $event
     * @return array|mixed
     */
    public function onCustomerSet(Event $event)
    {
        $array      = $event->getParams();
        $lastArray  = $event->getParam('lastArray');
        $form       = $event->getParam('form');

        if (class_exists(GoogleLogin::class)) {
            $form->add([
                'type'  => 'checkbox',
                'name'  => 'google_login_state',
                'attributes'    => [
                    'id'            => 'google_login_state',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'google_login_state',
                'required'  => false,
                'validators'=> [
                    [
                        'name'      => 'InArray',
                        'options'   => [
                            'haystack'  => [0, 1]
                        ]
                    ]
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('Google登录'),
                'inputName'     => 'google_login_state',
                'classSpanNum'  => 2,
                'type'          => 'checkbox',
                'style'         => 'style="width: 80px"',
                'helpUrl'       => [
                    'url'   => 'https://docs.loongdom.com.cn/plugin/shop/google-login.html',
                    'title' => $this->translator->translate('点击查看Google配置方法')
                ]
            ];

            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('回调地址'),
                'inputName'     => '',
                'classSpanNum'  => 8,
                'staticBody'    => str_replace(['https://', 'http://'], '', $event->getTarget()->url()->fromRoute('shop-user', ['action' => 'otherLoginCallBack', 'id' => 'google'], ['force_canonical' => true]))
            ];

            $form->add([
                'type'  => 'text',
                'name'  => 'google_app_id',
                'attributes'    => [
                    'id'            => 'google_app_id',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'google_app_id',
                'required'  => false,
                'filters'   => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags']
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('APP ID'),
                'inputName'     => 'google_app_id',
                'classSpanNum'  => 6
            ];

            $form->add([
                'type'  => 'text',
                'name'  => 'google_app_key',
                'attributes'    => [
                    'id'            => 'google_app_key',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'google_app_key',
                'required'  => false,
                'filters'   => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags']
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('APP KEY'),
                'inputName'     => 'google_app_key',
                'classSpanNum'  => 6
            ];
        }

        if (class_exists(FacebookLogin::class)) {
            $form->add([
                'type'  => 'checkbox',
                'name'  => 'facebook_login_state',
                'attributes'    => [
                    'id'            => 'facebook_login_state',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'facebook_login_state',
                'required'  => false,
                'validators'=> [
                    [
                        'name'      => 'InArray',
                        'options'   => [
                            'haystack'  => [0, 1]
                        ]
                    ]
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('Facebook登录'),
                'inputName'     => 'facebook_login_state',
                'classSpanNum'  => 2,
                'type'          => 'checkbox',
                'style'         => 'style="width: 80px"',
                'helpUrl'       => [
                    'url'   => 'https://docs.loongdom.com.cn/plugin/shop/facebook-login.html',
                    'title' => $this->translator->translate('点击查看Facebook配置方法')
                ]
            ];

            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('回调地址'),
                'inputName'     => '',
                'classSpanNum'  => 8,
                'staticBody'    => str_replace(['https://', 'http://'], '', $event->getTarget()->url()->fromRoute('shop-user', ['action' => 'otherLoginCallBack', 'id' => 'facebook'], ['force_canonical' => true]))
            ];

            $form->add([
                'type'  => 'text',
                'name'  => 'facebook_app_id',
                'attributes'    => [
                    'id'            => 'facebook_app_id',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'facebook_app_id',
                'required'  => false,
                'filters'   => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags']
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('APP ID'),
                'inputName'     => 'facebook_app_id',
                'classSpanNum'  => 6
            ];

            $form->add([
                'type'  => 'text',
                'name'  => 'facebook_app_key',
                'attributes'    => [
                    'id'            => 'facebook_app_key',
                    'class'         => 'form-control'
                ]
            ]);

            $form->inputFilter->add([
                'name'      => 'facebook_app_key',
                'required'  => false,
                'filters'   => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags']
                ]
            ]);
            $lastArray['formExtend'][] = [
                'inputTitle'    => $this->translator->translate('APP KEY'),
                'inputName'     => 'facebook_app_key',
                'classSpanNum'  => 6
            ];
        }

        $array['lastArray'] = $lastArray;
        $array['form']      = $form;
        $event->setParams($array);

        $lastArray['form'] = $form;
        return $lastArray;
    }

    /**
     * 商品咨询消息
     * @param Event $event
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function onAddGoodsConsultSystemNotice(Event $event)
    {
        $goodsInfo = $event->getParam('goodsInfo');

        $this->systemNoticeManager->addSystemNotice([
            'noticeTitle'   => $this->translator->translate('有新的商品咨询'),
            'noticeBody'    => $this->translator->translate('商品') . ' ' . $goodsInfo->getGoodsName(),
            'noticeTime'    => time(),
            'noticeType'    => 'goods',
            'noticeClass'   => 3    //任务
        ]);
    }

    /**
     * 商品评价消息
     * @param Event $event
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function onAddOrderGoodsEvaluationSystemNotice(Event $event)
    {
        $orderGoods = $event->getParam('orderGoodsInfo');

        $this->systemNoticeManager->addSystemNotice([
            'noticeTitle'   => $this->translator->translate('有新的商品评价'),
            'noticeBody'    => $this->translator->translate('商品') . ' ' . $orderGoods->getGoodsName(),
            'noticeTime'    => time(),
            'noticeType'    => 'order',
            'noticeClass'   => 2    //通知
        ]);
    }
}